package com.un.ebs.sys.uitl;


import cn.hutool.core.util.StrUtil;

import java.util.*;

/**
 * @author lin
 * @date 19/9/25
 */
public class SignUtils {

    /**
     * 生成签名
     *
     * @param map
     * @return
     */
    public static String getSign(Map<String, String> map, String endKey) {
        String result = "";
        try {
            String sb = getSignStr(map);
            result = MD5Util.md5Signature(sb).toUpperCase();
        } catch (Exception e) {
            return null;
        }
        return result;
    }

    public static String getSignStr(Map<String, String> map) {
        List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
        // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
        Collections.sort(infoIds, Comparator.comparing(Map.Entry::getKey));
        // 构造签名键值对的格式
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> item : infoIds) {
            if (item.getKey() != null || item.getKey() != "") {
                String key = item.getKey();
                Object val = item.getValue();
                if (!(val == "" || val == null) && !"sign".equalsIgnoreCase(key)) {
                    sb.append(key + "=" + val + "&");
                }
            }
        }
        String signStr = sb.toString();
        if (signStr.endsWith("&")) {
            signStr = signStr.substring(0, signStr.length() - 1);
        }
        return signStr;
    }

    /**
     * 签名检验
     */
    public static boolean checkSign(Map<String, String> map, String endKey, String sign) {
        String localSign = getSign(map, endKey);
        return StrUtil.isNotBlank(sign) && sign.equalsIgnoreCase(localSign);
    }

}
